package cn.ycc1.boot3video.video;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ParallelHlsGenerator {

    public static boolean generateMultiQualityHls(String inputPath, String outputDir) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        try {
            // 确保输出目录存在
            java.io.File dir = new java.io.File(outputDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 定义编码任务
            List<Future<Boolean>> futures = Arrays.asList(
                    executor.submit(() -> encodeQuality(inputPath, outputDir, "1080p", 2000, "1920:1080", "128k")),
                    executor.submit(() -> encodeQuality(inputPath, outputDir, "720p", 1000, "1280:720", "96k")),
                    executor.submit(() -> encodeQuality(inputPath, outputDir, "480p", 500, "854:480", "64k"))
            );

            // 等待所有任务完成
            for (Future<Boolean> future : futures) {
                if (!future.get()) {
                    return false;
                }
            }

            // 生成主播放列表 - 使用修正后的方法
            MasterPlaylistGenerator.generateSwitchableMasterPlaylist(outputDir);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            executor.shutdown();
        }
    }

    private static boolean encodeQuality(String inputPath, String outputDir,
                                         String quality, int videoBitrate,
                                         String resolution, String audioBitrate) {
        try {
            // FFmpeg编码命令...
            Process process = Runtime.getRuntime().exec(new String[]{
                    "ffmpeg", "-i", inputPath,
                    "-c:v", "libx264", "-c:a", "aac",
                    "-b:v", videoBitrate + "k",
                    "-maxrate", (int)(videoBitrate * 1.07) + "k",
                    "-bufsize", (int)(videoBitrate * 1.5) + "k",
                    "-b:a", audioBitrate,
                    "-g", "48", "-keyint_min", "48", "-sc_threshold", "0",
                    "-vf", "scale=" + resolution,
                    "-hls_time", "4", "-hls_list_size", "0",
                    "-hls_playlist_type", "vod",
                    "-hls_segment_filename", outputDir + "/" + quality + "_%03d.ts",
                    outputDir + "/" + quality + ".m3u8"
            });

            return process.waitFor() == 0;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
